/*
 * @Author: wangjq4214
 * @Date: 2022-05-03 21:18:47
 * @LastEditTime: 2022-05-03 22:33:12
 * @LastEditors: wangjq4214
 */

import {
  Form,
  Input,
  Space,
  Button,
  FormInstance,
} from '@arco-design/web-react';
import { IconUser, IconLock } from '@arco-design/web-react/icon';
import { settingsAtom, tokenAtom } from '@/models/global';
import { post } from '@/apis';
import { LOGIN_URL, LoginRes } from '@/apis/user';
import { loadingAtom } from '../model';

const FormItem = Form.Item;

const LoginFrom = () => {
  const formRef = useRef<FormInstance | null>();

  const navigate = useNavigate();

  const settings = useAtomValue(settingsAtom);
  const [loading, setLoading] = useAtom(loadingAtom);
  const setToken = useSetAtom(tokenAtom);

  const handleSubmit = () => {
    setLoading(true);
    formRef.current
      ?.validate()
      .then((values) => {
        return post<LoginRes>(LOGIN_URL, { ...values });
      })
      .then((data) => {
        setToken(data.token);
        navigate('/');
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return (
    <div className="w-320px">
      <div className="text-$color-text-1 font-medium text-24px leading-32px">
        登录{settings.title}
      </div>
      <div className="text-$color-text-3 text-16px leading-24px pb-32px">
        登录{settings.title}
      </div>

      <Form
        ref={(e) => {
          formRef.current = e;
        }}
        layout="vertical"
        onSubmit={handleSubmit}
      >
        <FormItem
          field="username"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input
            placeholder="请输入用户名"
            prefix={<IconUser />}
            onPressEnter={handleSubmit}
          />
        </FormItem>
        <FormItem
          field="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password
            placeholder="请输入密码"
            prefix={<IconLock />}
            onPressEnter={handleSubmit}
          />
        </FormItem>
        <Space size={16} direction="vertical">
          <Button type="primary" htmlType="submit" long loading={loading}>
            登录
          </Button>
        </Space>
      </Form>
    </div>
  );
};

export default LoginFrom;
